import React from 'react'
import classNames from 'classnames'
import { withNativeProps } from '../../utils/native-props'
import { warn } from '@/library/tool-kits/log'
import { useCheckList } from './context'
import List from '../List'
import type { CheckListItemProps } from './type'

const classPrefix = 'rt-check-list-item'

export const CheckListItem: React.FC<CheckListItemProps> = (props) => {
  const {
    disabled = false,
    description,
    isLink = false,
    onClick,
    prefix,
    readOnly = false,
    title,
    value,
    children,
  } = props
  const context = useCheckList()

  if (context === null) {
    warn(
      'CheckList.Item',
      'CheckList.Item can only be used inside CheckList.',
    )
    return null
  }

  const active = context.value.includes(value!)
  const actReadOnly = readOnly || context.readOnly
  const actDisabled = disabled || context.disabled
  const actIsLink = isLink || context.isLink

  const defaultExtra = active ? context.activeIcon : null
  const renderExtra = context.extra ? context.extra(active) : defaultExtra
  const extra = <div className={`${classPrefix}-extra`}>{renderExtra}</div>

  if (actIsLink && !onClick) {
    warn(
      'CheckList.Item',
      'you must have `onClick` props to navigate when `isLink` is true',
    )
  }

  const onHandlerClick = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
    if (actReadOnly) return

    if (actIsLink) {
      onClick?.(e)
      return
    }

    if (active) {
      context.uncheck(value!)
    } else {
      context.check(value!)
    }

    onClick?.(e)
  }

  return withNativeProps(
    props,
    <List.Item
      arrow={false}
      clickable={!actReadOnly}
      className={classNames(
        classPrefix,
        actReadOnly && `${classPrefix}-readonly`,
      )}
      disabled={actDisabled}
      description={description}
      extra={extra}
      onClick={onHandlerClick}
      prefix={prefix}
      title={title}
    >
      {children}
    </List.Item>,
  )
}

export default CheckListItem
